/**
 * 
 */
package de.oszimtcc.timetableservices;

import java.util.HashMap;
import java.util.Map;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import de.oszimtcc.framework.BaseActivity;
import de.oszimtcc.framework.BaseBinder;


/**
 * @author reuter
 *
 */
public class TimetableServiceConnection implements ServiceConnection
{
	private BaseActivity activity;
	Map<String, IBinder> connectedServices = new HashMap<String, IBinder>();
	
	public TimetableServiceConnection(BaseActivity pActivity)
	{
		this.activity = pActivity;
	}
	
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) 
	{
		Toast.makeText(this.activity, "Bound : " + name.getShortClassName(), Toast.LENGTH_SHORT).show();
		connectedServices.put(name.getShortClassName(), service);
	}
	
	
	@Override
	public void onServiceDisconnected(ComponentName name) 
	{
		connectedServices.remove(name.getShortClassName());
	}
	
	public void bindService(Class<? extends Service> pServiceToBind)
	{
		Intent serviceIntent = new Intent(activity, pServiceToBind);
		activity.bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
		activity.startService(serviceIntent);
	}
	
	@SuppressWarnings("unchecked")
    public <T extends Service> T getBoundedService(Class<T> pServiceToReturn) 
	{
	    return (T)((BaseBinder<T>)connectedServices.get(pServiceToReturn.getName())).getBinderService();
	}
}

